#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 解析和修改XML
问题: 你想读取一个XML文档，对它最一些修改，然后将结果写回XML文档。
提示 : 
"""

from xml.etree.ElementTree import parse, Element

filename = 'pred.xml'

def recipe1():
    doc = parse(filename)
    root = doc.getroot()
    print(root)

    # Remove a few elements
    root.remove(root.find('sri'))
    root.remove(root.find('cr'))

    # Insert a new element after <nm>...</nm>
    # root.getchildren().index(root.find('nm'))     # getchildren()方法在3.9中删除了
    e = Element('spam')
    e.text = 'This is a test'
    root.insert(2, e)

    # Write back to a file
    doc.write('06_rw_xml.xml', xml_declaration=True)

def main():
    print('recipe1'.center(20, '*'))
    recipe1()

if __name__ == '__main__':
    main()                    